#include "response.h"
#include "iostream"

using namespace easyWebServer;


Response::Response(int fd)
    : m_fd(fd)
{
    m_conn.setfd(fd);
}

Response::~Response()
{
    m_fileFd = -1;
}

void Response::setContext(const string & src, const string & httpCode, const string & http)
{
    m_out += http + " " + httpCode + "\r\n";
    for(auto it = m_context.begin(); it != m_context.end(); it++)
    {
        m_out += it->first + ": " + it->second + "\r\n";
    }
    m_out += "\r\n" + src;
}

string & Response::operator [] (const string & key)
{
    return m_context[key];
}

void Response::send()
{
    m_conn.sendData(m_out.c_str(), m_out.size());
    sendFile(m_fileFd);
}

void Response::insertPair(const string & key, const string & value)
{
    m_context[key] = value;
}

void Response::sendFile(int fd)
{
    if(fd == -1) return;
    m_conn.sendFile(fd);
}

void Response::setFileFd(int fd)
{
    m_fileFd = fd;
}

